package com.willpower.eureka.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.willpower.eureka.auth.response.Result;
import com.willpower.eureka.auth.response.ResultCode;
import com.willpower.eureka.entity.SysMenu;
import com.willpower.eureka.entity.SysUser;
import com.willpower.eureka.service.ISysMenuService;
import com.willpower.eureka.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wen-yi
 * @since 2021-11-05
 */
@Slf4j
@RestController
@RequestMapping("/users")
public class SysUserController {
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private ISysUserService sysUserService;

    @GetMapping
    public JSONObject list(@RequestParam(defaultValue = "") String query, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "2") Integer pageSize){
        log.info("query: {}, pageNum: {}, pageSize: {}", query,pageNum,pageSize);
        return sysUserService.selectPage(query, pageNum, pageSize);
    }

    @PreAuthorize("hasRole('admin')")
    @PostMapping
    public Result addUser(SysUser sysUser){
//        SysUser sysUser = new SysUser();
//        sysUser.setUsername(username);
//        sysUser.setPassword(password);
//        sysUser.setEmail(email);
//        sysUser.setNickname(nickname);
//        sysUser.setPhoneNumber(phoneNumber);
        sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
        log.info("addUser: {}",sysUser);
        return Result.ok(sysUserService.save(sysUser));
    }

    @GetMapping("/{id}")
    public Result getUserById(@PathVariable("id") Integer id){
        log.info("id: {}", id);
        return Result.ok(sysUserService.getById(id));
    }

    @PreAuthorize("hasRole('admin')")
    @PutMapping("/{id}")
    public Result updateUserById(@PathVariable("id") Integer id,SysUser sysUser){
        log.info("id: {}, sysUser: {}", id,sysUser);
        return Result.ok(sysUserService.updateById(sysUser));
    }

    @PreAuthorize("hasRole('admin')")
    @DeleteMapping("/{id}")
    public Result deleteUserById(@PathVariable("id") Integer id){
        log.info("id: {}", id);
        return Result.ok(sysUserService.removeById(id));
    }

    @PreAuthorize("hasRole('admin')")
    @PutMapping("/{id}/enabled/{enabled}")
    public Result changeUserStatus(@PathVariable("id") Integer id,@PathVariable("enabled") Boolean enabled){
        log.info("id: {}, enabled: {}", id,enabled);
        return Result.ok(sysUserService.changeUserStatus(id,enabled));
    }

}
